//
//  SecretListViewController.m
//  Secret
//
//  Created by 隋文涛 on 13-12-11.
//  Copyright (c) 2013年 隋文涛. All rights reserved.
//

#import "SecretListViewController.h"

@interface SecretListViewController ()

@end

@implementation SecretListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.tabBarController.tabBar setHidden:NO];
}


- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    [self CreatFilesPathInLibraryWithName:@"Notes"];
    arraydata = [[NSMutableArray alloc] init];
    
    [self Getarraydata];
}

- (void)Getarraydata{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    [arraydata removeAllObjects];
    [arraydata addObjectsFromArray:[fileManager subpathsAtPath:[self GetPathInLibraryWithName:@"Notes"]]];
    int32_t count = (int32_t)[arraydata count];
    for (int i = count-1; i > -1; i--) {
        NSString *name = [arraydata objectAtIndex:i];
        if (name == nil || name.length < 4) {
            [arraydata removeObject:name];
        }else{
            if (![name hasSuffix:@".dat"]) {
                [arraydata removeObject:name];
            }
        }
    }
}

- (NSString *)GetPathInLibraryWithName:(NSString *)name{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(
														 NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *LibraryDirectory = [paths objectAtIndex:0];
    return [LibraryDirectory stringByAppendingPathComponent:name];
}
//在Library下创建文件夹name
- (void)CreatFilesPathInLibraryWithName:(NSString *) name {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(
														 NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *LibraryDirectory = [paths objectAtIndex:0];
    NSString *imageDir = [LibraryDirectory stringByAppendingPathComponent:name];
    BOOL isDir = NO;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL existed = [fileManager fileExistsAtPath:imageDir isDirectory:&isDir];
    if ( !(isDir == YES && existed == YES) )
    {
        [fileManager createDirectoryAtPath:imageDir withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    //    删除文件夹及文件级内的文件：
    //    NSString *imageDir = [NSString stringWithFormat:@"%@/Caches/%@", NSHomeDirectory(), dirName];
    //    NSFileManager *fileManager = [NSFileManager defaultManager];
    //    [fileManager removeItemAtPath:imageDir error:nil];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [arraydata count];
}

- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *Identifier = @"Identifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:Identifier];
    }
    NSString *StringName = [arraydata objectAtIndex:indexPath.row];
    NSString *StringTime;
    NSString *Name;
    int32_t index_ = 0;
    for (int32_t i = 0; i < StringName.length; i++) {
        if ([StringName characterAtIndex:i] == '_') {
            index_ = i;
            break;
        }
    }
    if (index_ > 0) {
        NSRange range;
        range.location = 0;
        range.length = index_;
        StringTime = [StringName substringWithRange:range];
        
        if (index_ + 1 < StringName.length) {
            range.location = index_ + 1;
            range.length = (StringName.length - range.location - 4)>0?(StringName.length - range.location - 4):0;
            Name = [StringName substringWithRange:range];
        }
    }

    cell.textLabel.text = [@"  " stringByAppendingString:Name];
    cell.detailTextLabel.text = [@"  " stringByAppendingString:[PublicClass TimeFromInterval:StringTime]];
    
    NSLog(@"%@",[cell.contentView subviews]);
    return cell;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *LastName = [arraydata objectAtIndex:indexPath.row];
    NSString *path = [[self GetPathInLibraryWithName:@"Notes"] stringByAppendingPathComponent:LastName];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager removeItemAtPath:path error:nil];
    
    [arraydata removeObject:LastName];
    [tableView beginUpdates];
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
    [tableView endUpdates];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
//    SecretdetailViewController *Secretdetail = [[SecretdetailViewController alloc] init];
//    
//    [self.navigationController pushViewController:Secretdetail animated:YES];
}


//跳转操作
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    NSLog(@"sender:\n%@",sender);
    UITableViewCell *cell = (UITableViewCell *)sender;
    NSIndexPath *id = [self.tableview indexPathForCell:cell];
    NSString *LastName = [arraydata objectAtIndex:id.row];
    NSString *path = [[self GetPathInLibraryWithName:@"Notes"] stringByAppendingPathComponent:LastName];
    ((SecretdetailViewController *)segue.destinationViewController).path = path;
}


- (IBAction)Button_AddClicked:(id)sender {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"请输入标题" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    [alert textFieldAtIndex:0].delegate = self;
    [alert show];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (textField.text.length == 20) {
        string = @"";
    }
    if ([string isEqualToString:@" "])
        return NO;
    return YES;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        NSString *name = [alertView textFieldAtIndex:0].text;
        [alertView textFieldAtIndex:0].delegate = nil;
        if (name.length > 0) {
            NSString *time = [NSString stringWithFormat:@"%.0f",[PublicClass timeIntervalSince1970]];
            NSLog(@"time:%@+name:%@",time,name);
            NSString *LastName = [NSString stringWithFormat:@"%@_%@.dat",time,name];
            NSString *string = @"";
            NSString *path = [[self GetPathInLibraryWithName:@"Notes"] stringByAppendingPathComponent:LastName];
            NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
            [data writeToFile:path atomically:YES];
            
//            [data writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
            
            [arraydata addObject:LastName];
            [self.tableview beginUpdates];
            [self.tableview insertRowsAtIndexPaths:[NSArray arrayWithObject: [NSIndexPath indexPathForRow:([arraydata count]-1) inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
            [self.tableview endUpdates];
            
            [self performSelector:@selector(toWritePageWithPath:) withObject:path afterDelay:0.4];
        }
    }
}

- (void)toWritePageWithPath:(NSString *)path{
    SecretdetailViewController *SDV = [self.storyboard instantiateViewControllerWithIdentifier:@"SecretdetailViewController"];
    SDV.path = path;
    SDV.WriteMode = YES;
    [self.navigationController pushViewController:SDV animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
